package TopDNSServer;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.List;

/**
 * @Author: 0162977
 * @Date: 2020/12/3 16:07
 */
public class ListenThread implements Runnable {

    DatagramSocket socket = null;
    DatagramPacket packet = null;

    public ListenThread(DatagramSocket socket,DatagramPacket packet) {
        this.socket = socket;
        this.packet = packet;
    }

    @Override
    public void run() {
        String info = null;
        DatagramPacket packet2 = null;
        info = new String(packet.getData(), 0, packet.getLength());
        System.out.println(info);
        try {
            if (info.split(",")[0].equals("1") ){   //第一个字符是1，代表是查询请求
                String website = info.split(",")[1];   //获取要解析的域名
                String portReq = info.split(",")[2];
                if (ShareSpaceAndFun.addWait(website, Integer.parseInt(portReq))) {  //加入等待队列
                    //转发权限服务器
                    InetAddress address = InetAddress.getByName("localhost");
                    byte[] data2 = (website+","+ShareSpaceAndFun.myPort).getBytes();
                    packet2 = new DatagramPacket(data2, data2.length, address, ShareSpaceAndFun.getNextPort(website));
                    socket.send(packet2);
                }


            }else if (info.split(",")[0].equals("0") ){   //第一个字符是0，代表是查询结果
                String website = info.split(",")[1];   //获取要解析的域名0

                //转发根服务器
                InetAddress address = null;
                address = InetAddress.getByName("localhost");
                List<Integer> portWaitList = ShareSpaceAndFun.getWaitPortByWebsite(website);
                if (portWaitList != null) {
                    for (Integer port : portWaitList) {
                        //发回客户端
                        byte[] data2 = info.getBytes();
                        packet2 = new DatagramPacket(data2, data2.length, address, port);
                        socket.send(packet2);
                    }
                }
            }else if (info.split(",")[0].equals("2") ){   //第一个字符是2，代表是迭代式查询
                String website = info.split(",")[1];   //获取要解析的域名
                String portNext = info.split(",")[2];
                //转发本地服务器
                InetAddress address = null;
                address = InetAddress.getByName("localhost");

                byte[] data2 = ("2,"+website+","+ ShareSpaceAndFun.getNextPort(website)).getBytes();
                packet2 = new DatagramPacket(data2, data2.length, address, Integer.parseInt(portNext));
                socket.send(packet2);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}